package org.itzixi.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.itzixi.netty.single.ChannelGroupSingleton;

@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case READER_IDLE -> {
                    log.info("进入读空闲状态");
                }
                case WRITER_IDLE -> log.info("进入写空闲状态");
                default -> {
                    log.info("进入读写空闲状态");
                    log.error("channel关闭前, clients的数量为：{}", ChannelGroupSingleton.getInstance().size());
                    Channel channel = ctx.channel();
                    channel.close();
                    log.error("channel关闭后, clients的数量为：{}", ChannelGroupSingleton.getInstance().size());
                }
            }

        }
    }
}
